/*
 * @Description: 接口要加上文件目录/admin/chapters/xxx
 * @Author: cy
 * @Date: 2024/12/3
 */

var express = require("express");
var router = express.Router();
const { Op } = require("sequelize");

const { Chapter, Course,User } = require("../../models");
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");
const { NotFound, Forbidden } = require('http-errors');
const { log } = require("winston");

/**
 * 检查用户是否能浏览当前章节
 * @param req
 * @param chapter
 * @returns {Promise<void>}
 */
async function checkUserRole(req, chapter) {
  // 如果章节是免费的
  if (chapter.free) {
    return;
  }

  // 检查用户是否有权限访收费章节
  const allowedRoles = [1, 100]; // 会员和管理员的角色ID
  const user = await User.findByPk(req.userId);
  if (!allowedRoles.includes(user.role)) {
    throw new Forbidden('您没有权限浏览，请先购买会员后再访问。');
  }
}

/**
 * 公共方法：关联课程数据
 * @returns {{include: [{as: string, model, attributes: string[]}], attributes: {exclude: string[]}}}
 */
function getCondition() {
  return {
    attributes: { exclude: ["CourseId"] },
    include: [
      {
        model: Course,
        as: "course",
        attributes: ["id", "name"],
      },
    ],
  };
}

/**
 * 公共方法：查询当前章节
 */
async function getChapter(req,id) {
  const condition = getCondition();

  const chapter = await Chapter.findByPk(id, condition);
  if (!chapter) {
    throw new NotFoundError(`ID: ${id}的章节未找到。`);
  }
      // 检查用户是否能浏览当前章节
  await checkUserRole(req, chapter);

  return chapter;
}

/*
 * $param
 * @return
 * @desc 章节列表，带模糊搜索
 * select * from Chapters where title like '%标题 10%'`
 * 分页
 * SELECT * FROM `Chapters` LIMIT offset, pageSize;
 * SELECT * FROM `Chapters` LIMIT 0, 10;第一页
 * SELECT * FROM `Chapters` LIMIT 10, 10;第二页
 * offset = (currentPage - 1) * pageSize
 * */
router.get("/chaptersList", async function (req, res, next) {
  try {
    const query = req.query;
    if (!query.courseId) {
      throw new Error(`课程ID（courseId）不能为空。`);
    }
    // 当前是第几页，如果不传，那就是第一页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;

    // 每页显示多少条数据，如果不传，那就显示10条
    const pageSize = Math.abs(Number(query.pageSize)) || 10;

    // 计算 offset
    const offset = (currentPage - 1) * pageSize;

    // 定义查询条件
    const condition = {
      ...getCondition(),
      order: [
        ["id", "ASC"],
        ["rank", "ASC"],
      ],
      limit: pageSize,
      offset: offset,
    };
    //  where 条件中 ，通用查询条件
    if (
      Object.entries(query)?.filter(
        (e) => !["currentPage", "pageSize"]?.includes(e?.[0])
      )?.length > 0
    ) {
      let obj = {};
      Object.entries(query)
        ?.filter((e) => !["currentPage", "pageSize"]?.includes(e?.[0]))
        ?.map((item) => {
          let key = item[0];
          let value = item[1];
          obj[key] = {
            [Op.like]: `%${value}%`,
          };
        });
      obj.courseId = {
        [Op.eq]: query.courseId,
      };
      condition.where = obj;
    }

    // const data = await Chapter.findAll(condition);
    const { count, rows } = await Chapter.findAndCountAll(condition);
    success(res, "查询章节列表成功", {
      status: true,
      message: "查询章节列表成功。",
      data: {
        chapters: rows,
        pagination: {
          total: count,
          currentPage,
          pageSize,
        },
      },
      query,
    });
  } catch (error) {
    failure(res, error);
  }

  // res.json({
  //   status: true,
  //   message: "查询章节列表成功。",
  //   data: {
  //     chapters: rows,
  //     pagination: {
  //       total: count,
  //       currentPage,
  //       pageSize,
  //     },
  //   },
  //   query,
  // });
});
/* 根据ID获取章节详情 */
router.get("/", async function (req, res, next) {
  console.log(req.query);
  
  try {
    const chapter = await getChapter(req,req.query.id);
    // 查询章节详情
    success(res, "查询章节成功。", { chapter });
  } catch (e) {
    // 如果没有找到，就抛出异常
    failure(res, e);
  }
});

/* 新增或者修改章节 */
router.post("/addOrUpdateChapter", async function (req, res, next) {
  try {
    //根据ID区分创建还是更新
    if (req.body.id) {
      const chapter = await getChapter(req,id);

      // 使用 req.body 获取到用户通过 POST 提交的数据，然后创建章节
      await chapter.update(req.body, {
        where: { id: req.body.id },
      });
      success(res, "更新成功。", { chapter }, 200);
    } else {
      const chapter = await Chapter.create(req.body);
      success(res, "创建成功。", { chapter }, 201);
    }
  } catch (error) {
    failure(res, error);
  }
});

/* 删除章节 */
router.delete("/deleteChapterById", async function (req, res, next) {
  try {
    // 使用 req.body 获取到用户通过 POST 提交的数据，然后删除章节
    /*
     * $param
     * @return
     * @desc 或者先查询章节后，再删除，比如你想提示文字不存在，未找到，如下
     * const chapter = await Chapter.findByPk(id);
     * await chapter.destroy();
     * */
    const chapter = await Chapter.destroy({ where: { id: req.body.id } });

    res.status(200).json({
      status: true,
      message: "操作成功。",
      data: chapter,
    });
  } catch (error) {
    res.status(500).json({
      status: false,
      message: "操作失败。",
      errors: [error.message],
    });
  }
});

module.exports = router;
